'use strict' //开启严格模式

const http = require('http')

let html=`
    <!DOCTYPE html>
    <html>
        <head>
            <title>First Server</title>
        </head>
        <body>
            <div>Node.js in service</div>
        </body>
    </html>
    `

let routerTable={
    '/':async(request,response)=>{
        response.setHeader('content-type','text/html;charset=utf-8')
        response.end(html)
    },

    '/x/y':async(request,response)=>{
        response.end('--ok--')
    },

    '/x/y/z':async(request,response)=>{
        let bufferList=[]
        let totalLength=0

        request.on('data',chunk=>{
            totalLength+=chunk.length//记录字节数
            bufferList.push(chunk)
        })

        let bodyData=null

        request.on('end',()=>{//bodyData彻底接受完毕触发end
            if(bufferList.length>0){
                bodyData=Buffer.concat(bufferList,totalLength)//把所有的buffer小片段拼在一起
            }
            bufferList=[];

            //等到bodyData数据全部接收完执行
            if(bodyData){
                response.setHeader('content-type','text/plain;charset=utf-8')
                response.end(bodyData)
            }else{
                response.end()
            }
        })
    }
}

//在request响应之前头部文件已经解析完了
let serv = http.createServer((request, response) =>{

    if(routerTable [request.url]===undefined){
        response.statusCode=404
        response.end('page not found')
        return
    }

    routerTable[request.url](request,response)//如果request.url符合'/'，则执行后面的函数

    // console.log(request.url,request.headers,request.method)服务端解析的url为:/x/y

    // if(request.url!=='/x/y/z'){//防止恶意访问
    //     response.statusCode=404
    //     response.end('page not found')
    //     return
    // }

    

    // response.setHeader('content-type','text/html;charset=utf-8')
    
 
})

serv.listen(3456) // 3456是端口号


// 在文件所在地打开git bash
// 输入node 文件名.js
// 在浏览器打开'http://localhost:端口号'